<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Overtrue\EasySms\EasySms;

class SendSmsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     */
    public $tries = 5;

    /**
     * 无任务的时候睡眠时间。
     */
    public $sleep = 60;

    /**
     * 任务运行的超时时间。
     */
    public $timeout = 120;

    protected $param;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($param)
    {
        $this->param = $param;
    }

    /**
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
     */
    public function handle()
    {
        foreach ($this->param as $p) {
            $code = rand(1000, 9999);
            $easySms = new EasySms(config('easysms'));

            $temp = [
                'content'  => '',
                'template' => 'SMS_139945046',
                'data' => ['code' => $code],
            ];
            $easySms->send($p, $temp);
        }
    }

    /**
     * 要处理的失败任务。
     */
    public function failed(Exception $exception)
    {
        Log::info('短信发送失败 ' . $this->param);
    }
}
